<?php

namespace App\Http\Controllers\Port;

use App\Http\Controllers\ScoreRuleController;
use App\Models\CompetiteActivityDatabase;
use App\Models\CompetiteActivityEbook;
use App\Models\CompetiteActivityWorksDatabase;
use App\Models\CompetiteActivityWorksEbook;
use App\Models\ReadingTask;
use App\Models\ReadingTaskAppointUser;
use App\Models\ReadingTaskDatabase;
use App\Models\ReadingTaskExecute;
use App\Models\ReadingTaskExecuteDatabase;
use App\Models\ReadingTaskExecuteWorks;
use App\Models\UserLibraryInfo;
use App\Validate\ReadingTaskValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 阅读任务
 */
class ReadingTaskController extends CommonController
{
    public $model = null;
    public $validate = null;
    public $taskDatabaseModel = null;
    public $score_type = 23;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ReadingTask();
        $this->validate = new ReadingTaskValidate();
        $this->taskDatabaseModel = new ReadingTaskDatabase();
    }

    /**
     * 阅读任务列表(我的阅读任务)
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(作品数据库名称)
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $user_id = request()->user_info['id'];

        $field = ['id', 'title', 'img', 'start_time', 'end_time', 'browse_num', 'intro','is_reader', 'create_time'];
        $res = $this->model->lists($field, $keywords, $user_id, 1, null, null, null, null, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        //判断阅读进度
        $readingTaskExecuteModel = new ReadingTaskExecute();
        $readingTaskExecuteDatabaseModel = new ReadingTaskExecuteDatabase();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['intro'] = strip_tags($val['intro']);
            $progress = $readingTaskExecuteModel->where('user_id', $user_id)->where('task_id', $val['id'])->value('progress');
            $res['data'][$key]['progress'] = $progress; //阅读总进度
            $res['data'][$key]['status'] = $this->model->getReadingTaskStatus($val['id']); //阅读任务状态
            //查询下面的电子书数据库
            $task_database_list = $this->taskDatabaseModel->getReadingTaskDatabaseList($val['id']);
            //获取阅读进度
            foreach ($task_database_list as $k => $v) {
                $database_progress = $readingTaskExecuteDatabaseModel->where('user_id', $user_id)
                    ->where('task_id', $val['id'])->where('database_id', $v['database_id'])->value('progress');
                $task_database_list[$k]['progress'] = $database_progress ? $database_progress : 0;
            }
            $res['data'][$key]['task_database_list'] = $task_database_list; //阅读数据库

            // dump($val);die;
            $res['data'][$key]['start_time'] = $val['start_time'] ? date('Y-m-d H:i', strtotime($val['start_time'])) : null;
            $res['data'][$key]['end_time'] = $val['end_time'] ? date('Y-m-d H:i', strtotime($val['end_time'])) : null;
        }

        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 阅读任务详情
     * @param id int 任务id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = request()->user_info['id'];

        $res = $this->model->detail($this->request->id, ['id', 'title', 'img', 'intro', 'create_time', 'is_reader', 'browse_num']);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        //添加浏览量
        $res->browse_num = ++$res->browse_num;
        $res->save();

        $readingTaskExecuteModel = new ReadingTaskExecute();
        $progress = $readingTaskExecuteModel->where('user_id', $user_id)->where('task_id', $res['id'])->value('progress');
        $res['progress'] = $progress ? $progress : 0; //阅读总进度


        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }


    /**
     * 阅读任务数据库作品列表
     * @param task_id int 阅读任务id
     * @param database_id int 数据库id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(数据库作品名称)
     * @param type datetime 类型  1 作品  2 电子书
     */
    public function worksList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_database_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $task_id = $this->request->task_id;
        $database_id = $this->request->database_id;
        $user_id = $this->request->user_info['id'];
        $type = $this->request->type;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $database_info = CompetiteActivityDatabase::where('id', $database_id)->where('is_del', 1)->where('is_play', 1)->first();
        if (empty($database_info)) {
            return $this->returnApi(203, "当前数据库信息不存在");
        }
        $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
        $res = $competiteActivityWorksDatabaseModel->lists($database_id, $keywords, $type, null, null, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        //判断作品是否已读
        $readingTaskExecuteWorksModel = new ReadingTaskExecuteWorks();
        foreach ($res['data'] as $key => $val) {
            if ($user_id) {
                $is_reading = $readingTaskExecuteWorksModel->isReadingWorks($user_id, $task_id, $val['database_id'], $val['type'], $val['works_id'], $val['ebook_id']);
                $res['data'][$key]['is_reading'] = $is_reading ? true : false;
            } else {
                $res['data'][$key]['is_reading'] = false;
            }
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", "YES", $res);
    }


    /**
     * 阅读任务 电子书详情+电子书作品列表
     * @param ebook_id int 电子书id
     */
    public function ebookDetail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_ebook_detail_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $ebook_id = $this->request->ebook_id;
        $competiteActivityEbookModel = new CompetiteActivityEbook();
        //添加数据库浏览量
        $ebook_info = $competiteActivityEbookModel->select('id', 'name', 'img', 'intro', 'author', 'browse_num')
            ->where('id', $ebook_id)->where('is_del', 1)->where('is_play', 1)->first();
        if (empty($ebook_info)) {
            return $this->returnApi(203, "当前电子书信息不存在");
        }
        //添加浏览量
        $ebook_info->browse_num = ++$ebook_info->browse_num;
        $ebook_info->save();

        $ebook_info = $ebook_info->toArray();
        $competiteActivityWorksEbookModel = new CompetiteActivityWorksEbook();
        $res = $competiteActivityWorksEbookModel->lists($ebook_id, null, null, null, 999);

        // if (empty($res['data'])) {
        //     return $this->returnApi(203, "暂无数据");
        // }
        $ebook_info['work_list'] = $res['data'];

        //  $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", "YES", $ebook_info);
    }
    /**
     * 用户阅读任务记录表
     * @param task_id 阅读任务id
     * @param database_id 数据库id
     * @param type 类型  1 作品  2 电子书  与下面2个参数对应
     * @param works_id 作品id 
     * @param ebook_id 作品id
     */
    public function readingTaskReading()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_reading_task_reading')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $database_id = $this->request->database_id;
        $task_id = $this->request->task_id;
        $type = $this->request->type;
        $works_id = $this->request->works_id;
        $ebook_id = $this->request->ebook_id;
        if ($type == 1 && empty($works_id)) {
            return $this->returnApi(202, "作品ID不能为空");
        }
        if ($type == 2 && empty($ebook_id)) {
            return $this->returnApi(202, "电子书ID不能为空");
        }
        //判断自己是否有阅读的权限
        $reading_task_info = $this->model->where('id', $task_id)->where('is_del', 1)->where('is_play', 1)->first();
        if (empty($reading_task_info)) {
            return $this->returnApi(202, "阅读任务不存在");
        }
        if ($reading_task_info['start_time'] > date('Y-m-d H:i:s') || $reading_task_info['end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(202, "阅读任务未开始或已结束");
        }


        //判断是否需要绑定读者证
        if ($reading_task_info->is_reader == 1) {
            //判断读者证号密码是否正确 和是否绑定读者证
            $userLibraryInfoModel = new UserLibraryInfo();
            $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id, $account_id);
            if (is_string($account_lib_info)) {
                return $this->returnApi(204, $account_lib_info);
            }
        }

        if (config('other.is_need_score') && !empty($account_id) && $reading_task_info['is_reader'] == 1) {
            $scoreRuleObj = new ScoreRuleController();
            $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $user_id, $account_id);
            if ($score_status['code'] == 202 || $score_status['code'] == 203) $res['is_can_make'] = '积分不足不能参加此阅读';
        }

        if ($reading_task_info['is_appoint'] == 1) {
            //判断当前用户是否是执行用户
            $is_appoint = ReadingTaskAppointUser::where('user_id', $user_id)->where('task_id', $task_id)->first();
            if (empty($is_appoint)) {
                return $this->returnApi(203, "无权限阅读"); //也是返回203，不做处理
            }
        }
        DB::beginTransaction();
        try {
            $reading_task_info->browse_num = ++$reading_task_info->browse_num;
            $reading_task_info->save();

            $progress = $this->model->readingTaskReading($user_id, $account_id, $task_id, $database_id, $type, $works_id, $ebook_id);

            //如果进度是 100 才能增加
            if ($progress == '100' && config('other.is_need_score') === true  && $reading_task_info->is_reader == 1) {
                $scoreRuleObj = new ScoreRuleController();
                $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $user_id, $account_id);
                if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);
                if ($score_status['code'] == 200) {
                    $scoreRuleObj->scoreChange($score_status, $user_id, $account_id, 0); //添加积分消息
                }
            }

            DB::commit();
            return $this->returnApi(200, '阅读成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }
}
